﻿using System.Collections.Generic;
using System.Web.Http;
using DefaultConnection;
using MementoWeb.Models;
using MementoLibrary.DTOs;
using AutoMapper;
using System;
using MementoLibrary;

namespace MementoWeb.Controllers
{
    public class WorkLogController: ApiController
    {
        private readonly IDataRepository _dataRepository;

        public WorkLogController(IDataRepository dataRepository)
        {
            _dataRepository = dataRepository;
        }

        public IEnumerable<WorkLog> Get()
        {
            return _dataRepository.GetAllWorkLogs();
        }

        public IEnumerable<WorkLogDTO> GetByDateRange(DateTime from, DateTime to)
        {
            return _dataRepository.GetWorklogsForUserByDateRange(PersonId, from, to);
        }
        
        public WorkLog GetById(int id)
        {
            return _dataRepository.GetWorkLogById(id);
        }

        public WorklogSavedResult Post(WorkLogDTO workLog)
        {
            var workLogEntity = PrepareWorkLogEntity(workLog);
            var worklogId = _dataRepository.CreateNewWorkLog(workLogEntity);
            _dataRepository.BulkCreateWorkCategories(worklogId, workLog.CategoryIDs);
            return new WorklogSavedResult { WorklogId = worklogId };
        }

        private WorkLog PrepareWorkLogEntity(WorkLogDTO workLog, WorkLog workLogEntity = null)
        {
            if (workLogEntity == null)
            {
                workLogEntity = new WorkLog();
            }
            Mapper.Map(workLog, workLogEntity);
            var projectID = _dataRepository.CreateOrUpdateProject(workLog.Task.Project);
            var taskID = _dataRepository.CreateOrUpdateTask(workLog.Task, projectID);
            workLogEntity.TaskId = taskID;
            workLogEntity.PersonId = PersonId;
            return workLogEntity;
        }

        public WorklogSavedResult Put(WorkLogDTO workLog)
        {
            var existingWorklog = _dataRepository.GetWorkLogById(workLog.WorkLogId);
            if (existingWorklog.PersonId != PersonId)
            {
                throw new Exception();
            }
            var workLogEntity = PrepareWorkLogEntity(workLog, existingWorklog);
            _dataRepository.SaveWorkLogChanges(workLogEntity);
            _dataRepository.BulkCreateWorkCategories(workLog.WorkLogId, workLog.CategoryIDs);
            return new WorklogSavedResult { WorklogId = workLogEntity.WorkLogId };
        }

        public void Delete(int id)
        {
            _dataRepository.DeleteWorkLog(id);
        }

        private int? _personId;

        private int PersonId
        {
            get
            {
                if (!_personId.HasValue)
                {
                    _personId = _dataRepository.GetOrCreatePersonId(User.Identity.Name);
                }
                return _personId.Value;   
            }
        }

    }
}
